import { ref } from 'vue'
import { defineStore } from 'pinia'
import { accountLogin, getUserInfoById, getUserMenuByRoleId } from '@/service/module/login'
import type { IAccount } from '@/types'
import { localCache } from '@/utils/cache'
// 从router文件中获取的router
import router from '@/router'

export const useLoginStore = defineStore('login', () => {
  // store
  const token = ref<string>(localCache.getCache('token') ?? '')
  const userInfos = ref<any>({})
  const userMenu = ref<any[]>(localCache.getCache('menu') ?? [])
  // actions
  // 登录业务逻辑
  async function getLoginAccount(account: IAccount) {
    const results = await accountLogin(account)
    const id = results.data.id
    token.value = results.data.token
    const name = results.data.name
    // 持久化存储
    localCache.setCache('token', token.value)
    // 获取用户的角色
    const userInfosData = await getUserInfoById(id)
    userInfos.value = userInfosData.data
    localCache.setCache('userInfo', userInfosData.data)
    // 获取菜单
    const userMenuResults = await getUserMenuByRoleId(userInfos.value.role.id)
    localCache.setCache('menu', userMenuResults.data)
    // 页面跳转
    router.push('/main')
  }
  return { token, userInfos, userMenu, getLoginAccount }
})
